#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author Jmz

from django.shortcuts import render,HttpResponse,redirect

# Create your views here.
from app01.models import Books



def books(request):
    #查
    data = Books.objects.all()
    return render(request,"app01/index.html",{'data':data})

def add_book(request):
    if request.method == 'GET':
        return render(request,"app01/addbook.html")
    else:
        try:
            # 添加
            title = request.POST.get('title')
            pubDate = request.POST.get('pubDate')
            price = request.POST.get('price')
            publish = request.POST.get('publish')
            Books.objects.create(
                title=title
                ,pubDate=pubDate
                ,price =price
                ,publish=publish
            )
            return redirect('/')
        except Exception as e:
            return render(request,"error.html",{'content':e})

        

def update(request,id):
    if request.method =='GET':
        info = Books.objects.filter(id=id).first()
        if not info:
            return render(request,"404.html",{'content':"没有任何数据"})
        else:
            return render(request,"app01/updatebook.html",{"info":info})
    else:
        try:
            title = request.POST.get('title')
            pubDate = request.POST.get('pubDate')
            price = request.POST.get('price')
            publish = request.POST.get('publish')
            Books.objects.filter(id=id).update(
                title=title
                , pubDate=pubDate
                , price=price
                , publish=publish
            )
            return redirect('/')
        except Exception as e:
            return render(request,"error.html",{'content':e})



def delete(request,id):
    Books.objects.filter(id=id).delete()
    return redirect('/')


def not_found(request):
    return render(request,"404.html",{'content':"没有任何数据"})